package client

import (
	"fmt"
	"strings"
	"time"
	"yunj/app/service/client/logservice"
	"yunj/pkg/global"
	"yunj/pkg/util"
	"yunj/pkg/yunj/core/response"
	yunjUtil "yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

// 捕获panic
func Recover(ctx *gin.Context, recovered any) {
	var err error
	if rErr, ok := recovered.(error); ok {
		err = rErr
	} else {
		err = fmt.Errorf("%v", recovered)
	}
	fmt.Printf("全局panic错误捕获%T：%v", recovered, recovered)
	// 日志记录
	appendArgs := logservice.AppendArgs{
		EndTime:         time.Now().In(time.Local), // 计算耗时
		ResponseContent: yunjUtil.FormatError(err),
	}
	logservice.Record(ctx, appendArgs)
	// 是否跳转到提示页
	if !yunjUtil.IsAsync(ctx) && !strings.HasPrefix(ctx.Request.RequestURI, "/tips") {
		util.RedirectError(ctx, err.Error())
	}
	// 文件错误日志记录
	global.Logger.Error(yunjUtil.FormatError(err))
	response.FailJsonData(err.Error()).Response(ctx)
	ctx.Abort()
}
